<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/*数字资源-资源每天阅读表*/

class ResourceBookReadDay extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_book_read_day';

    /**
     * 添加用户阅读时间
     * @param read_duration 阅读时长  单位分钟
     */
    public function addReadBookDay($resource_guid, $resource_business_id, $big_type_id=null,  $date = null, int $read_duration = 1)
    {
        $date = $date ? $date : date('Y-m-d');
        $res = $this->where('resource_guid', $resource_guid)->where('resource_business_id', $resource_business_id)->where('date', $date)->first();
        if (empty($res)) {
            $res = $this;
        } else {
            $read_duration = $res->read_duration + $read_duration;
        }
        $res->resource_guid = $resource_guid;
        $res->resource_business_id = $resource_business_id;
        $res->big_type_id = $big_type_id;
        $res->date = $date;
        $res->read_duration = $read_duration; //阅读时长
        $res->save();
        return true;
    }
}
